package com.zivwu.mvp.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.zivwu.mvp.view.IView;
import com.zivwu.utils.device.FragmentHelper;
import com.zivwu.utils.device.ToastHelper;

import dagger.android.support.DaggerDialogFragment;


public abstract class IFragment extends DaggerDialogFragment
        implements IView {
    Context mContext;
    private DialogFragment mProgress;

    private int res;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }


    @Nullable
    @Override
    public Context getContext() {
        return mContext;
    }


    @Override
    public void finish() {
        FragmentActivity activity = getActivity();
        if (activity != null)
            activity.finish();
    }


    public void setRes(int res) {
        this.res = res;
    }


    public int getRes() {
        return res;
    }

    @Override
    public void showDialog(DialogFragment fragment) {
        FragmentHelper.showDialog(fragment, getChildFragmentManager());
    }


    protected void replaceFragment(IFragment fragment,
                                   FragmentManager manager,
                                   Pair<View, String>... sharedElements) {
        replaceFragment(fragment,
                manager,
                false,
                sharedElements);
    }

    protected void replaceFragment(IFragment fragment,
                                   FragmentManager manager,
                                   boolean addToBackStack,
                                   Pair<View, String>... sharedElements) {
        FragmentHelper.replace(fragment.getRes(),
                fragment,
                manager,
                addToBackStack,
                sharedElements);
    }


    /* ************************same*****************************/


    @Override
    public Bundle getTransitionBundle() {
        return ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity()).toBundle();
    }


    @Override
    public void showToast(String msg) {
        ToastHelper.showMsg(msg);
    }

    @Override
    public void showToast(int id) {
        showToast(getString(id));
    }


    @Override
    public void onLoadStart() {
        if (mProgress == null)
            mProgress = getLoadingDialog();
        showDialog(mProgress);
    }

    protected abstract DialogFragment getLoadingDialog();

    @Override
    public void onLoadFinish() {
        if (mProgress != null)
            mProgress.dismissAllowingStateLoss();
    }
}
